#include "adbutils.h"
#include <QtCore/QProcess>
#include "settings.h"

AdbUtils::AdbUtils(QObject *parent) : QObject(parent)
{
}

QMutex AdbUtils::mutex;
QAtomicPointer<AdbUtils> AdbUtils::instance = 0;

AdbUtils* AdbUtils::getInstance()
{
#ifndef Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE
    if(!QAtomicPointer<AdbUtils>::isTestAndSetNative())
        qDebug("Error: TestAndSetNative not supported!");
#endif

    if(instance.testAndSetOrdered(0, 0))
    {
        QMutexLocker locker(&mutex);
        instance.testAndSetOrdered(0, new AdbUtils);
    }
    return instance;
}

QString AdbUtils::excute_adb(QString cmd, bool shell) {
    QProcess process;
    QStringList cmd_list = cmd.split(" ");
    if (shell)
        cmd_list.insert(0, "shell");
    Settings *settings = Settings::getInstance();
    QString program = settings->getAdbPath();
    if (program.length() <= 0) {
        return QString("ERROR");
    }
    QStringList arguments;
    for (int i = 0; i < cmd_list.size(); ++i) {
        arguments.append(cmd_list[i]);
    }
    qDebug() << "excute_adb" << program << "; params" << arguments;
    process.start(program, arguments);
    process.waitForFinished();
    QByteArray error = process.readAllStandardError();
    QByteArray out = process.readAllStandardOutput();
    qDebug() << "error" << error << "out" << out;
    return QString(out);
}
